package com.david.SendFileToGateway.encoder;

import feign.RequestTemplate;
import feign.codec.EncodeException;
import feign.form.ContentType;
import feign.form.FormEncoder;

import feign.codec.Encoder;
import feign.form.MultipartFormContentProcessor;
import feign.form.spring.SpringManyMultipartFilesWriter;
import feign.form.spring.SpringSingleMultipartFileWriter;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Type;
import java.util.Collections;
import java.util.Map;

import static feign.form.ContentType.MULTIPART;


public class MultipartSpringEncoder extends FormEncoder {

    public MultipartSpringEncoder(){
        this(new Encoder.Default());
    }


    public MultipartSpringEncoder(Encoder delegate){
        super(delegate);
        MultipartFormContentProcessor processor=(MultipartFormContentProcessor)getContentProcessor(MULTIPART);
        processor.addWriter(new SpringSingleMultipartFileWriter());
        processor.addWriter(new SpringManyMultipartFilesWriter());
    }

    @Override
    public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {
        //单个MultipartFile判断
        if (bodyType.equals(MultipartFile.class)){
            MultipartFile file=(MultipartFile) object;
            Map data = Collections.singletonMap(file.getName(), template);
            super.encode(data,MAP_STRING_WILDCARD,template);
            return;
        }else if (bodyType.equals(MultipartFile[].class)){//MutipartFile数组进行处理
            MultipartFile[] file=(MultipartFile[])object;
            if (file!=null){
                Map data = Collections.singletonMap(file.length == 0 ? "" : file[0].getName(), object);
                super.encode(data,MAP_STRING_WILDCARD,template);
                return;
            }
        }
        //如果是其他类型则调用父类的默认处理方法
        super.encode(object,bodyType,template);
    }
}
